R Array
Array is R data type which has multiple dimensions.
array()
function creates or tests for arrays.
dim()
function defines the dimension of an array.
array(data=NA, dim=length(data), dimnames=NULL)
data
: vector to fill the array
dim
: row and col numbers
:
...
Example
theArray <- array(1:24,c(2,3,4))
dimnames(theArray) = list(
c("row1", "row2"),
c("col1", "col2", "col3"),
c("layer1", "layer2", "layer3", "layer4"))
theArray[,,"layer4"]
> x <- array(1:9)
> x
[1] 1 2 3 4 5 6 7 8 9
> x <- array(1:9,c(3,3))
> x
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
> x <- 1:64
> dim(x) <- c(2,4,8) #dim() converts the vector into array
> is.array(x)
[1] TRUE
> x
, , 1
[,1] [,2] [,3] [,4]
[1,] 1 3 5 7
[2,] 2 4 6 8
, , 2
[,1] [,2] [,3] [,4]
[1,] 9 11 13 15
[2,] 10 12 14 16
, , 3
[,1] [,2] [,3] [,4]
[1,] 17 19 21 23
[2,] 18 20 22 24
, , 4
[,1] [,2] [,3] [,4]
[1,] 25 27 29 31
[2,] 26 28 30 32
, , 5
[,1] [,2] [,3] [,4]
[1,] 33 35 37 39
[2,] 34 36 38 40
, , 6
[,1] [,2] [,3] [,4]
[1,] 41 43 45 47
[2,] 42 44 46 48
, , 7
[,1] [,2] [,3] [,4]
[1,] 49 51 53 55
[2,] 50 52 54 56
, , 8
[,1] [,2] [,3] [,4]
[1,] 57 59 61 63
[2,] 58 60 62 64
> x[1,,]
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 9 17 25 33 41 49 57
[2,] 3 11 19 27 35 43 51 59
[3,] 5 13 21 29 37 45 53 61
[4,] 7 15 23 31 39 47 55 63
> x[1,2,]
[1] 3 11 19 27 35 43 51 59
> x[1,2,1]
[1] 3
Ways to create arrays
- Common ways to create vectors (or one-dimensional arrays)
include:
> a <- c(3, 7, 9, 11) # Concatenates numeric values into a vector
> a <- c("a", "b", "c") # Concatenates character strings into a vector
> a <- 1:5 # Creates a vector of integers from 1 to 5 inclusive
> a <- rep(1, times = 5) # Creates a vector of 5 repeated `1's
To manipulate a vector:
> a[10] # Extracts the 10th value from the vector `a'
> a[5] <- 3.14 # Inserts 3.14 as the 5th value in the vector `a'
> a[5:7] <- c(2, 4, 7) # Replaces the 5th through 7th values with 2, 4, and 7
Unlike larger arrays, vectors can be extended without first
creating another vector of the correct length. Hence,
> a <- c(4, 6, 8)
> a[5] <- 9 # Inserts a 9 in the 5th position of the vector,
# automatically inserting an `NA' values position 4
- A factor vector is a special type of
vector. R creates this special class of vector from a pre-existing vector x
using the factor() command, which separates x into levels
based on the discrete values observed in x. These values may be
either integer value or character strings. For example,
> x <- c(1, 1, 1, 1, 1, 2, 2, 2, 2, 9, 9, 9, 9)
> factor(x)
[1] 1 1 1 1 1 2 2 2 2 9 9 9 9
Levels: 1 2 9
By default, factor() creates unordered factors, which are
treated as discrete, rather than ordered, levels. Add the optional
argument ordered = TRUE to order the factors in the vector:
> x <- c("like", "dislike", "hate", "like", "don't know", "like", "dislike")
> factor(x, levels = c("hate", "dislike", "like", "don't know"),
+ ordered = TRUE)
[1] like dislike hate like don't know like dislike
Levels: hate < dislike < like < don't know
The factor() command orders the levels according to the order in
the optional argument levels. If you omit the levels command,
R will order the values as they occur in the vector. Thus, omitting
the levels argument sorts the levels as like < dislike <
hate < don't know in the example above. If you omit one or more
of the levels in the list of levels, R returns levels values of NA for the missing level(s):
> factor(x, levels = c("hate", "dislike", "like"), ordered = TRUE)
[1] like dislike hate like <NA> like dislike
Levels: hate < dislike < like
Use factored vectors within data frames for plotting, to set the values of the explanatory variables using
setx and in the ordinal logit and multinomial
logit models.
- Build matrices (or two-dimensional arrays) from vectors
(one-dimensional arrays). You can create a matrix in two ways:
- From a vector: Use the command matrix(vector, nrow
= 3
, ncol = 2
) to create a
matrix from the vector by filling in the columns from left to
right. For example,
> matrix(c(1,2,3,4,5,6), nrow = 2, ncol = 3)
[,1] [,2] [,3] # Note that when assigning a vector to a
[1,] 1 3 5 # matrix, none of the rows or columns
[2,] 2 4 6 # have names.
- From two or more vectors of equal length
: Use cbind() to
combine 2
vectors vertically to form a
matrix,
or rbind() to combine 2
vectors horizontally to form a
matrix. For example:
> x <- c(11, 12, 13) # Creates a vector `x' of 3 values.
> y <- c(55, 33, 12) # Creates another vector `y' of 3 values.
> rbind(x, y) # Creates a 2 x 3 matrix. Note that row
[,1] [,2] [,3] # 1 is named x and row 2 is named y,
x 11 12 13 # according to the order in which the
y 55 33 12 # arguments were passed to rbind().
> cbind(x, y) # Creates a 3 x 2 matrix. Note that the
x y # columns are named according to the
[1,] 11 55 # order in which they were passed to
[2,] 12 33 # cbind().
[3,] 13 12
R supports a variety of matrix functions, including:
det(), which returns the matrix's determinant;
t(), which transposes the matrix;
solve(), which inverts the the matrix; and
%*%, which multiplies two matricies.
In addition, the dim() command returns the dimensions of your matrix.
As with vectors, square brackets extract specific values from a matrix and the
assignment mechanism <- replaces values. For example:
> loo[,3] # Extracts the third column of loo.
> loo[1,] # Extracts the first row of loo.
> loo[1,3] <- 13 # Inserts 13 as the value for row 1, column 3.
> loo[1,] <- c(2,2,3) # Replaces the first row of loo.
If you encounter problems replacing rows or columns, make sure that
the dims() of the vector matches the dims() of the
matrix you are trying to replace.
- An n-dimensional array is a set of stacked matrices of identical
dimensions. For example, you may create a three dimensional array by stacking 2
matrices each with 2 rows and 3 columns.
> a <- matrix(8, 2, 3) # Creates a 2 x 3 matrix populated with 8's.
> b <- matrix(9, 2, 3) # Creates a 2 x 3 matrix populated with 9's.
> array(c(a, b), c(2, 3, 2)) # Creates a 2 x 3 x 2 array with the first
, , 1 # level [,,1] populated with matrix a (8's),
# and the second level [,,2] populated
[,1] [,2] [,3] # with matrix b (9's).
[1,] 8 8 8
[2,] 8 8 8 # Use square brackets to extract values. For
# example, [1, 2, 2] extracts the second
, , 2 # value in the first row of the second level.
# You may also use the <- operator to
[,1] [,2] [,3] # replace values.
[1,] 9 9 9
[2,] 9 9 9
If an array is a one-dimensional vector or two-dimensional matrix, R
will treat the array using the more specific method.
Three functions especially helpful for
arrays:
- is() returns both the type of scalar value that populates
the array, as well as the specific type of array (vector, matrix, or
array more generally).
- dims() returns the size of an array, where
> dims(b)
[1] 33 5
indicates that the array is two-dimensional (a matrix), and has 33
rows and 5 columns.
- The single bracket
[ ]
indicates specific values in the
array. Use commas to indicate the index of the specific values you
would like to pull out or replace:
> dims(a)
[1] 14
> a[10] # Pull out the 10th value in the vector `a'
> dims(b)
[1] 33 5
> b[1:12, ] # Pull out the first 12 rows of `b'
> c[1, 2] # Pull out the value in the first row, second column of `c'
> dims(d)
[1] 1000 4 5
> d[ , 3, 1] # Pulls out a vector of 1,000 values
How to Create an Array in R
You have two different options for constructing matrices or arrays. Either you use the creator functions matrix() and array(), or you simply change the dimensions using the dim() function.
Use the creator functions in R
You can create an array easily with the array() function, where you give the data as the first argument and a vector with the sizes of the dimensions as the second argument. The number of dimension sizes in that argument gives you the number of dimensions. For example, you make an array with four columns, three rows, and two tables like this:
> my.array <- array(1:24, dim=c(3,4,2))
> my.array
, , 1
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
, , 2
[,1] [,2] [,3] [,4]
[1,] 13 16 19 22
[2,] 14 17 20 23
[3,] 15 18 21 24
This array has three dimensions. Notice that, although the rows are given as the first dimension, the tables are filled column-wise. So, for arrays, R fills the columns, then the rows, and then the rest.
Change the dimensions of a vector in R
Alternatively, you could just add the dimensions using the dim() function. This is a little hack that goes a bit faster than using the array() function; it’s especially useful if you have your data already in a vector. (This little trick also works for creating matrices, by the way, because a matrix is nothing more than an array with only two dimensions.)
Say you already have a vector with the numbers 1 through 24, like this:
> my.vector <- 1:24
You can easily convert that vector to an array exactly like my.array simply by assigning the dimensions, like this:
> dim(my.vector) <- c(3,4,2)
If you check how my.vector looks like now, you see there is no difference from the array my.array that you created before.
You can check whether two objects are identical by using the identical() function. To check, for example, whether my.vector and my.array are identical, you simply do the following:
> identical(my.array, my.vector)
[1] TRUE